﻿//
// Created by Administrator on 2025/7/8.
//
#include <iostream>
#include <thread>
#include <mutex>
// 功能： 防止多个线程同时访问共享资源。
int counter = 0;
std::mutex mtx;

void add() {
    for (int i = 0; i < 10000; ++i) {
        std::lock_guard<std::mutex> lock(mtx);  // 自动加锁解锁
        ++counter;
    }
}

int main() {
    std::thread t1(add), t2(add);
    t1.join(); t2.join();
    std::cout << "counter = " << counter << std::endl;
    return 0;
}
